package com.astrofizzbizz.raspberrypicamera.server;

import java.io.File;
import java.util.Date;

import com.astrofizzbizz.raspberrypicamera.client.RaspberryPiService;
import com.astrofizzbizz.raspberrypicamera.shared.RaspberryPiException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class RaspberryPiServiceImpl extends RemoteServiceServlet implements
		RaspberryPiService 
{
	@Override
	public String[] takeSingleImage(String imageName, int holdOffTime, String switchSettings, boolean debug, String[] debugResponse) throws RaspberryPiException 
	{
		String imageDir = getServletContext().getRealPath("cameraImages/stills");
		String command = "raspistill  -o " + imageDir + "/" + imageName + " -t " + Integer.toString(holdOffTime) + switchSettings;
		String[] response;
		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		if (debug) 
		{
			System.out.println(new Date().toString() + " Take Single Image: " + command);
			try {Thread.sleep(holdOffTime);} catch (InterruptedException e) {}
			return debugResponse;
		}
		response  = ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors); 
		return response;
	}
	@Override
	public String[] getLatestTimeLapseImageName(boolean debug, String[] debugResponse) throws RaspberryPiException 
	{
		if (debug) return debugResponse;
		String imageDir = getServletContext().getRealPath("cameraImages/timeLapse");
		String command =  "ls -Art " + imageDir + "/*.jpg | tail -n 2";
		String[] response;
		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		String latestFileName = null;
		File latestFile = null;
		String[] returnInfo ={null, null};
		try {Thread.sleep(300);} catch (InterruptedException e) {}
		response = ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);
		if (response[0].length() > 3)
		{
			latestFile = new File(response[0]);
			latestFileName =  latestFile.getName();
			long age = new Date().getTime() - latestFile.lastModified();
			age = age / 1000;
			age = age / 60;
			returnInfo[0] = latestFileName;
			returnInfo[1] = Long.toString(age);
		}
		return returnInfo;
	}
	@Override
	public String[] clearDirectory(String directory, String wildCardExtenstion, boolean debug, String[] debugResponse) throws RaspberryPiException
	{
		if (debug) return debugResponse;
		String[] response = {null, null};
		String totalPath = getServletContext().getRealPath(directory);
		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		String command = "";

		command = "rm " + totalPath + "/" + wildCardExtenstion;
		response = ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);
		return response;
	}
	@Override
	public String[] isRaspistillRunning(boolean debug, String[] debugResponse) throws RaspberryPiException
	{
		if (debug) return debugResponse;
		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		String command = "";

		try {Thread.sleep(300);} catch (InterruptedException e) {}
		command = "ps aux | grep raspistill";
		String[] response = ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);
		return response;
	}
	@Override
	public String[] killRaspistill(boolean debug, String[] debugResponse) throws RaspberryPiException
	{
		if (debug) return debugResponse;
		String[] response = {null, null};
		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		String command = "";

		command = "killall raspistill";
		response = ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);
		return response;
	}
	@Override
	public String startTimeLapse(String intervalString, String maxTimeString, String maxNumImagesString, String switchSettings, boolean debug, String debugResponse) throws RaspberryPiException
	{
		double dinterval = Double.parseDouble(intervalString);
		dinterval = dinterval * 1000;
		int interval = (int) dinterval;
		
		double dmaxTime = Double.parseDouble(maxTimeString);
		dmaxTime = dmaxTime * 1000;
		int maxTime = (int) dmaxTime;

		int maxImages = Integer.parseInt(maxNumImagesString);
		if (maxImages > 9999) maxImages = 9999;

		boolean linux = true;
		boolean getInfo = true;
		boolean expDebug = false;
		boolean ignoreErrors = false;
		String command = "";
		String imageDir = getServletContext().getRealPath("cameraImages/timeLapse");

		if (debug) return debugResponse;
		command = "rm " + imageDir + "/*.*";
		if (!debug) ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);
		try {Thread.sleep(300);} catch (InterruptedException e) {}
		
		command = "raspistill -o " + imageDir + "/temp_%04d.jpg -tl " + Integer.toString(interval) + " -t " + Integer.toString(maxTime) + switchSettings + " &";
		if (!debug) ServerUtilities.runExternalProcess(command, linux, getInfo, expDebug, ignoreErrors);

		return command;
	}
}
